/* 原则上不直接修改data的数据 */
let data = {
  day: 1,
  week: 1,
  cash: 500,
  waitingList: [],
  customersOnTable: [],
  cookList: [{
    state: "free"
  }, {
    state: "free"
  },{
    state: "free"
  }]
}

/* 厨师解雇和招聘：上一个监听器 */
let prevShowListener = null;
let prevHindListener = null;

/* 阻塞消息 */
let hasMessage = false;

/* 实现加速功能 */
let acc = false;

/* 点菜队列，先进先出 */
let queue = [];

/* 菜品信息 */
let dishes = [
  {
    name: "凉拌SAN",
    type: "liangcai"
  },
  {
    name: "冷切DOM",
    type: "liangcai"
  },
  {
    name: "UL抄LI",
    type: "zhucai"
  },
  {
    name: "红烧HEAD",
    type: "zhucai"
  },
  {
    name: "酥炸ECharts",
    type: "zhucai"
  },
  {
    name: "炙烤CSS",
    type: "zhucai"
  },
  {
    name: "清蒸DIV",
    type: "zhucai"
  },
  { 
    name: "鲜榨flex",
    type: "yinpin"
  },
  {
    name: "小程序奶茶",
    type: "yinpin"
  },
]

/* 实现解绑监听的功能 */
let quitButtonListener = null;
let orderButtonListenner = null

/* 桌号对应的订单 */
let orderList = {
  1: {
    list:[],
    total: 0,
    id: 0
  },
  2: {
    list:[],
    total: 0,
    id: 0
  },
  3: {
    list:[],
    total: 0,
    id: 0
  },
  4: {
    list:[],
    total: 0,
    id: 0
  }
};

/* 顾客个人信息，类数组对象 */
let customers = {
  1: {
    name: "QIAN",
    state: "possible"
  },
  2: {
    name: "SUN",
    state: "possible"
  },
  3: {
    name: "LI",
    state: "possible"
  },
  4: {
    name: "MA",
    state: "possible"
  },
  5: {
    name: "GUO",
    state: "possible"
  },
  6: {
    name: "LIU",
    state: "possible"
  },
  7: {
    name: "ZHANG",
    state: "possible"
  },
}

/* 清空子节点 */
function clear(ele) {
  while(ele.firstChild) {
    ele.removeChild(ele.firstChild);
  }
}

/* 打开菜单 */
function showMenu(id, seatNumber) {
  const menu = document.getElementById("menu");
  const quitButton = document.getElementById("quit");
  const orderButton = document.getElementById("order");
  const menuAvatar = document.getElementById("menu_avatar");
  const title = document.getElementById("menu_title");
  const list = document.getElementsByName("menu");    // 获取所有的checkbox项
  const newListener = () => {handleQuit(id, seatNumber)};
  quitButton.removeEventListener("click", quitButtonListener);
  quitButton.addEventListener("click", newListener);
  quitButtonListener = newListener;
  customers[id].state = "ordering";
  list.forEach((item)=>{
    item.addEventListener("change", ()=>{handleChange(id, seatNumber, orderButton)});
  });
  title.innerHTML = `${customers[id].name}正在点菜`;
  menuAvatar.innerHTML = `<div class="avatar${id} avatar"></div>`;
  menu.style.display = "block";
}

/* 不吃了，直接离开 */
function handleQuit(id, no) {
  const menu = document.getElementById("menu");
  const seat = document.getElementById(`seat${no}`);
  setCustomersOnTable(id, "remove");
  seat.className = "cir";
  seat.innerHTML = '';
  menu.style.display = "none";
  customers[id].state = "impossible"; // 今天不再来
  clearForm();
}

/* 点餐 */
function handleOrder(id, no) {
  const form = document.getElementsByName("menu");
  const menu = document.getElementById("menu");
  const list = orderList[no].list;
  orderList[no].id = id;
  // 遍历表单
  form.forEach((item, index) => {
    if(item.checked) {
      list.push({
        state: "cooking",
        ...dishes[index]
      });
    }
  })
  customers[id].state = "ready"; // 预备用餐状态
  menu.style.display = "none";
  showMessage(`${customers[id].name}完成点餐，等候用餐\n疯狂点击厨师头像可以加速做菜！`, "remind", 3000);
  clearForm();
  handleOrderFinished(id, no);
}

/* 点餐完毕 */
function handleOrderFinished(id, no) {
  const dishList = orderList[no].list;
  const length = dishList.length;
  for(let i = 0; i < length; i++) {
    let queueItem = {
      name: dishList[i].name,
      type: dishList[i].type,
      state: "cooking",
      no
    }
    queue.push(queueItem);  //将菜单全部推入全局队列中，等候处理
  }
  cookingFood();
}

/* 烹饪 */
function cookingFood() {
  const cookList = data.cookList;
  for(let key in cookList) {
    if(cookList[key] === null) {
      continue;
    }
    if(cookList[key].state === "free" && queue.length !== 0) {
      let newDish = queue.shift();
      const ele = document.getElementById(`cook${(+key)+1}`);
      ele.addEventListener("click", accelerate);
      cookList[key].state = "cooking";
      ele.className = "cir_cooking";
      attachCookingProgress(ele, "cooking", newDish, 10000, key);
    }
  }
}

/* 厨师渲染 */
function renderCookList(again) {
  // if(again) {
  //   for(let key in data.cookList) {
  //     const cook = document.getElementById(`cook${+(key)+1}`);
  //     // 删除按钮
  //     if(data.cookList[key].state === "cooking") {
  //       const chef = cook.querySelector(".chef");
  //       cook.removeChild(chef);
  //     }
  //     if(data.cookList[key].state === "free") {
  //       decorate = '<div class="delete">×</div>';
  //     }
  //     cook.innerHTML = '<div class="chef">'+decorate+'</div>';
  //   }
  //   return;
  // }
  const cooknode = document.getElementById("cook");
  for(let key in data.cookList) {
    const avatar = document.createElement("div");
    let decorate = '';
    if(data.cookList[key].state === "free") {
      avatar.className = "cir";
    }
    if(data.cookList[key].state === "free") {
      decorate = `<div class="delete" id="delete_button" onclick="showChefMessage(${key}, 'fire')">×</div>`;
    }
    avatar.innerHTML = '<div class="chef">'+decorate+'</div>';
    avatar.id = `cook${+(key)+1}`
    cooknode.appendChild(avatar);
  }
  /* 添加厨师功能 */
  if(data.cookList.length < 6) {
    const avatar = document.createElement("div");
    const key = data.cookList.length;
    avatar.className = "cir";
    avatar.id = `cook${key+1}`;
    avatar.innerHTML = `<div class='no-chef' id='add_icon' onclick="showChefMessage(${key}, 'advertise')"></div>`;
    cooknode.appendChild(avatar);
  }
}

// 加速起子
function accelerate() {
  acc = true;
}

function attachCookingProgress(ele, classname, newDish, time, key) {
  const progress = document.createElement("progress");
  const progressText = document.createElement("span");
  const chef = ele.querySelector(".chef");
  const deleteButton = chef.querySelector(".delete");
  ele.style.position = "relative";
  progressText.innerHTML = newDish.name;
  progressText.className = "progress";
  progress.className = classname;
  progress.max = 100;
  chef.removeChild(deleteButton);
  let flag = 0;
  acc = false; // 重置
  let timer = setInterval(() => {
    flag = acc ? flag + 10 : flag + 1;
    acc = false;  // 重置
    progress.value = flag;
    // 制作完成，直接上菜
    if(flag >= progress.max) {
      clearInterval(timer);
      ele.removeChild(progress);
      ele.removeChild(progressText);
      ele.removeEventListener("click", accelerate);
      ele.className = "cir";
      chef.innerHTML = `<div class="delete" id="delete_button" onclick="showChefMessage(${key}, 'fire')">×</div>`;
      data.cookList[key].state = "free";
      cookingFood();                     // 看看需不需要继续做菜(重要)
      renderCustomerDish(newDish);
    }
  }, time/100);
  ele.appendChild(progress);
  ele.appendChild(progressText);
}

function showChefMessage(key, action) {
  const message = document.getElementById(action);
  const yesButton = document.getElementById(`${action}_y`);
  const noButton = document.getElementById(`${action}_n`);
  if(action === "advertise") {
    prevShowListener = (e)=>{addChef(e, key, action)};
    yesButton.addEventListener("click", prevShowListener);
  } else {
    prevShowListener = (e)=>{deleteChef(e, key, action)};
    yesButton.addEventListener("click", prevShowListener);
  }
  prevHindListener = (e) => {hindChefMessage(e, action)};
  noButton.addEventListener("click", prevHindListener);
  message.style.display = "flex";
}

function hindChefMessage(e, action) {
  const message = document.getElementById(action);
  e.target.removeEventListener("click", prevHindListener);
  message.style.display = "none";
}

function deleteChef(e, key, action) {
  const ele = document.getElementById(`cook${(+key)+1}`);
  const message = document.getElementById(action);
  // 解约金
  e.target.removeEventListener("click", prevShowListener);
  if(!setCash(140, "reduce")) {
    message.style.display = "none";
    showMessage("你的金额已经不足以支付解约金", "warn", 2000);
    return;
  } else {
    showMessage("解约厨师成功！解约支出￥140", "remind", 2000);
  }
  data.cookList[key] = null;
  clear(ele);
  message.style.display = "none";
  ele.innerHTML = `<div class='no-chef' id='add_icon' onclick="showChefMessage(${key}, 'advertise')"></div>`;
}

function addChef(e, key, action) {
  const cooknode = document.getElementById("cook");
  data.cookList[key] = { state: "free" };
  const ele = document.getElementById(`cook${(+key)+1}`);
  e.target.removeEventListener("click", prevShowListener);
  const decorate = `<div class="delete" id="delete_button" onclick="showChefMessage(${key}, 'fire')">×</div>`;
  ele.innerHTML = '<div class="chef">'+decorate+'</div>';
  const message = document.getElementById(action);
  message.style.display = "none";
  showMessage(`招聘厨师成功！您已经拥有${getCookNumber()}名厨师`, "remind", 2000);
  /* 补充添加头像 */
  if(key + 1 === data.cookList.length && data.cookList.length <= 5) {
    const avatar = document.createElement("div");
    const extrakey = data.cookList.length;
    avatar.className = "cir";
    avatar.id = `cook${extrakey+1}`;
    avatar.innerHTML = `<div class='no-chef' id='add_icon' onclick="showChefMessage(${extrakey}, 'advertise')"></div>`;
    cooknode.appendChild(avatar);
  }
}

function getCookNumber() {
  let number=0;
  for(let key in data.cookList) {
    if(data.cookList[key]) {
      number++;
    }
  }
  return number;
}

function checkOrderList(no) {
  const {list, id, total} = orderList[no];
  if(list.length === 0) {
    setCash(total, "add");
    showMessage(`&nbsp&nbsp&nbsp&nbsp${customers[id].name}完成用餐，收获 ￥ ${total}`,"remind", 5000);
    handleQuit(id, no);
  } else {
    return;
  }
}

function renderCustomerDish(dish) {
  const { no, type, name } = dish;
  const ele = document.getElementById(`seat${no}`);
  const containor = ele.querySelector(".seat_dish");
  const div = document.createElement("div");
  div.className = "dish_containor";
  let time;
  const progress = document.createElement("progress");
  const progressText = document.createElement("span");
  progressText.innerHTML = name;
  progressText.className = "progress";
  if(type === "liangcai") {
    time = 5000;
  } else if (type === "yinpin") {
    time = 5000;
  } else if (type === "zhucai") {
    time = 8000;
  }
  progress.max = 100;
  let flag = 0;
  let timer = setInterval(() => {
    flag++;
    progress.value = flag;
    if(flag >= progress.max) {
      clearInterval(timer);
      const list = orderList[no].list;
      for(let key in list) {
        if(list[key].name === name) {
          list.splice(key, 1);
        }
      }
      checkOrderList(no);
      containor.removeChild(div);
    }
  }, time/100);
  div.appendChild(progress);
  div.appendChild(progressText);
  containor.appendChild(div);
}

/* 处理顾客入座 */
function handleSeat(id) {
  if(data.customersOnTable.length >= 4) {
    return;
  }
  const waiting = document.getElementById("waiting");
  const cus_delete = document.getElementById(`waiting_customer${id}`);
  const seatNumber = data.customersOnTable.length + 1;
  const seat = document.getElementById(`seat${seatNumber}`);
  const containor = document.createElement("div");
  containor.className = "seat_dish";
  customers[id].state = "ordering";
  seat.className = "cir_onTable";
  setCustomersOnTable(id, "add");
  setWaitingList(id, "remove");
  waiting.removeChild(cus_delete);
  seat.innerHTML = `<div class="avatar${id} avatar"></div>`;
  seat.appendChild(containor);
  showMenu(id, seatNumber);
}

/* 处理复选框的变化 */
function handleChange(id, no, button) {
  const listener = () => {handleOrder(id, no)};
  if(judgeCando()) {
    button.className = "";
    button.removeEventListener("click", orderButtonListenner);
    button.addEventListener("click", listener);
    orderButtonListenner = listener;
  } else {
    button.removeEventListener("click", orderButtonListenner);
    button.className = "cannot";
  }
  const title = document.getElementById("menu_title");
  let price = totalPrice();
  orderList[no].total = price;
  title.innerHTML = `${customers[id].name} 正在点菜, 已点￥${price} 的菜`;
}

/* 清空表格 */
function clearForm() {
  const list = document.getElementsByName("menu");
  list.forEach((item)=>{
    item.checked = false;
  });
}

/* 判断菜单是否合法 */
function judgeCando() {
  const list = document.getElementsByName("menu");
  let liangcai = 0,
      zhucai = 0,
      yinpin = 0;
  for(let i = 0; i < 2; i++) {
    if(list[i].checked) {
      liangcai++;
    }
  }
  for(let i = 2; i < 7; i++) {
    if(list[i].checked) {
      zhucai++;
    }
  }
  for(let i = 7; i < 9; i++) {
    if(list[i].checked) {
      yinpin++;
    }
  }
  if(liangcai <= 1 && zhucai === 1 && yinpin <= 1) {
    return true;
  } else return false;
}

/* 得到总价 */
function totalPrice() {
  const list = document.getElementsByName("menu");    // 获取所有的checkbox项
  let price = 0;
  list.forEach((item)=>{
    if(item.checked === true) {
      price += (+item.value);
    }
  });
  return price;
}

/* 显示消息，可复用 */
function showMessage(text, type, time) {
  if(hasMessage) {
    setTimeout(showMessage.bind(window, ...arguments), 1000);
    return;
  }
  hasMessage = true;
  const info = document.getElementById("info");
  const infoText = document.getElementById("info_text");
  if(type === "warn") {
    info.className = "info info_warn";
  } else if(type === "remind") {
    info.className = "info info_remind";
  }
  infoText.innerHTML = text;
  info.style.display = "flex";
  const timeout = setTimeout(() => {
    clearTimeout(timeout);
    hasMessage = false;
    info.style.display = "none";
  }, time);
  info.addEventListener("click", ()=>{
    clearTimeout(timeout);
    hasMessage = false;
    info.style.display = "none";
  });
}

function renderDate() {
  let date = document.getElementById("date");
  date.innerHTML = `W${data.week}&nbsp&nbsp&nbspD${data.day}`;
}

function renderCash() {
  let cash = document.getElementById("cash");
  cash.innerHTML = `${data.cash}`;
}

function setWaitingList(id, type) {
  if(type === "add") {
    data.waitingList.push(id);
    console.log(data.waitingList);
  } else if(type === "remove") {
    data.waitingList.splice(data.waitingList.indexOf(id), 1);
    console.log(data.waitingList);
  }
}

function setCustomersOnTable(id, type) {
  if(type === "add") {
    data.customersOnTable.push(id);
    console.log("table",data.customersOnTable);
  } else if(type === "remove") {
    data.customersOnTable.splice(data.customersOnTable.indexOf(id), 1);
    console.log("table",data.customersOnTable);
  }
}

function setCash(cash, type) {
  if(type === "add") {
    data.cash += cash;
    renderCash();
    return true;
  } else if (type === "reduce") {
    if(cash > data.cash) {
      return false;
    } else {
      data.cash -= cash;
      renderCash();
      return true;
    }
  }
}

/* 新的一天 */
function setDate() {
  if(data.day === 7) {
    data.week++;
    /* 周结算 */
    if(!setCash(getCookNumber()*100, "reduce")) {
      showMessage("当前资金不足以维持餐厅运营，游戏失败。", "warn", 5000);
    }
    data.day = 1;
  } else {
    data.day++;
  }
  for(let key in customers) {
    if(customers[key].state === "impossible") {
      customers[key].state ="possible";
    }
  }
}

/* 等待列表增加顾客 */
function newCustomerWaiting(id) {
  if(customers[id].state !== "possible") {
    return;
  }
  // state === "possible"
  const watingTime = 6000;
  const waiting = document.getElementById("waiting");
  const newCustomer = document.createElement("div");
  const avatar = document.createElement("div");
  const progress = document.createElement("progress");
  const progressText = document.createElement("span");
  progressText.innerHTML = "等位中";
  progress.max = 100;
  let flag = 0;
  customers[id].state = "waiting";
  let timer = setInterval(()=>{
    flag++;
    progress.value = flag;
    /* 顾客等待超时 */
    if(flag >= progress.max && customers[id].state === "waiting") {
      clearInterval(timer);
      setWaitingList(id, "remove");
      customers[id].state = "impossible"; // 今天不再来
      waiting.removeChild(newCustomer);
    }
  }, watingTime/100);
  avatar.className = `avatar${id} avatar`;
  newCustomer.appendChild(avatar);
  newCustomer.appendChild(progress);
  newCustomer.appendChild(progressText);
  newCustomer.id = `waiting_customer${id}`;
  newCustomer.addEventListener("click", ()=>{handleSeat(id)});
  newCustomer.className =  "customer cus_waiting";
  setWaitingList(id, "add");
  /* 延时通知，改善体验 */
  if(data.customersOnTable.length <= 3) {
    showMessage("餐厅目前有空位，赶紧点击客人头像让客人入座就餐吧!", "warn", 2000);
  }
  waiting.appendChild(newCustomer);
}

function init() {
  let welcome = document.getElementById("welcome");
  let id = 1;
  welcome.style.display = "none";
  renderCash();
  renderDate();
  renderCookList(false);
  newCustomerWaiting(id);
  setInterval(() => {
    id++;
    if(data.waitingList.length < 5 && id <= 7 && customers[id].state === "possible") {
      newCustomerWaiting(id);
    } else if (id === 8) {
      console.log(customers);
      id = 0;
    }
  }, 3000);
  setInterval(() => {
    setDate();
    renderDate();
    console.log(customers);
  }, 24000);
}

// 初始化
let start = document.getElementById("start");
start.addEventListener("click", init);

function recal() {
  const designWidth = 500;
  let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
  let htmlDom = document.getElementsByTagName('html')[0] || document.documentElement;
  htmlDom.style.fontSize= htmlWidth/designWidth + 'px';
}

// Rem
window.onresize = recal;
window.onload = recal;


